package cn.zyl.demo.qle.express;

import cn.zyl.demo.qle.bean.ISafeQleBean;
import cn.zyl.demo.qle.bean.SafeQleBean;
import com.ql.util.express.IExpressContext;
import org.springframework.context.ApplicationContext;

import java.util.HashMap;
import java.util.Map;

/**
 * SpringQLEContext类说明（单例模式）: 扩展QlExpress原来的上下文,来管理和调用spring的bean
 * <p>个人考虑：通过接口暴露给外界，可能会有安全问题</p>
 * <p><a href="https://blog.csdn.net/express_wind/article/details/84230455">扩展QLExpress来管理spring的bean</a></p>
 *
 * @author z.y.l
 * @version v1.0
 * @date 2020-08-28
 */
@SuppressWarnings("serial")
public class SpringExpressContext<K,V>  extends HashMap<K,V> implements IExpressContext<K,V> {
    private final ApplicationContext context;
    public SpringExpressContext(ApplicationContext applicationContext){
        this.context = applicationContext;
    }
    public SpringExpressContext(Map<K,V> map, ApplicationContext applicationContext){
        super(map);
        this.context = applicationContext;
    }
    /** 抽象方法：根据名称从属性列表中提取属性值 */
    @Override
    @SuppressWarnings("unchecked")
    public V get(Object name){
        V r = super.get(name);
        try{
            if( null == r && this.context != null && this.context.containsBean(name.toString())){
                //如果在Spring容器中包含bean，则返回String的Bean
                r = (V)this.context.getBean(name.toString());
                //如果不是可以操作的bean，将返回空
                if(!(r instanceof ISafeQleBean)){
                    r = (V)new SafeQleBean();
                }
            }
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return  r;
    }
    @Override
    public V put(K k, V v){
        return super.put(k,v);
    }
}
